﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.IO;

namespace Eugenhome.Atrium.LibRu.Web
{
    /// <summary>
    /// 
    /// </summary>
    public partial class libruconverter : System.Web.UI.Page
    {
        /// <summary></summary>
        private string _proxyAddress;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                _proxyAddress = WebConfigurationManager.AppSettings[DAO.WEBCONFIG_HOSTINGPROXY_KEY] != null ? WebConfigurationManager.AppSettings[DAO.WEBCONFIG_HOSTINGPROXY_KEY] : "";
                txtTargetFileName.Enabled = true;
                btnSave.Visible = Label2.Enabled = repItems.Visible = true;
                repFiles.Visible = false;
            }
            else
            {
                if (Request.QueryString["del"] != null && Request.QueryString["del"].Equals("true"))
                {
                    try
                    {
                        File.Delete(Server.MapPath(Path.Combine(LibRuBookFile.FILEFOLDER, Request.QueryString["file"])));
                    }
                    catch (Exception ex)
                    {
                        Response.Write(ex.Message);
                    }
                }

                //Label2.Visible = Label4.Visible = txtTargetFileName.Visible = 
                    btnSave.Visible = repItems.Visible = false;
                btnResultDownload.Visible = Label3.Visible = false;

                repFiles.Visible = true;

                List<BaseFile> files = new LibRuBookFile("").GetFiles(Server.MapPath(""));
                repFiles.DataSource = files;
                repFiles.DataBind();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLoad_Click(object sender, EventArgs e)
        {
            PageContent pc = new PageContent(txtUrl.Text, _proxyAddress);

            if (!pc.Content.IndexOf("<DL>", StringComparison.OrdinalIgnoreCase).Equals(-1))
            {
                Session["items"] = pc.Content.Split(new string[] { "<DL>" }, StringSplitOptions.None).Select(item => new LibRuItem(txtUrl.Text, item)).Where(item => item.Valid).ToList();
            }
            else
            {
                Session["items"] = pc.Content.Split(new string[] { "<tt>" }, StringSplitOptions.None).Select(item => new LibRuItem(txtUrl.Text, item)).Where(item => item.Valid).ToList();
            }

            repItems.DataSource = Session["items"];
            repItems.DataBind();

            //Label2.Visible = Label4.Visible = txtTargetFileName.Visible = 
                btnSave.Visible = repItems.Visible = true;
            btnResultDownload.Visible = Label3.Visible = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            List<LibRuItem> items = (List<LibRuItem>)Session["items"];

            string mode = "";

            foreach (int id in Request.Form.AllKeys.Where(item => item.StartsWith("item")).Where(item => !Request.Form[item].Equals(string.Empty)).OrderBy(item => Request.Form[item]).
                Select(item => Convert.ToInt32(item.Replace("item", ""))))
            {
                LibRuItem libruitem = items.Where(item => item.ID.Equals(id)).FirstOrDefault();
                if (libruitem != null)
                {
                    PageContent pc = new PageContent(libruitem.Link, _proxyAddress);
                    LibRuBookItem bookItem = new LibRuBookItem(pc.Content);
                    if (bookItem.Valid)
                    {
                        mode = bookItem.Mode;
                        string filename = txtTargetFileName.Text.Equals(string.Empty) ? Path.GetFileName(new Uri(libruitem.Link).LocalPath) : txtTargetFileName.Text;
                        try
                        {
                            LibRuBookFile lrbf = new LibRuBookFile(Server.MapPath(Path.Combine(LibRuBookFile.FILEFOLDER, filename)));
                            lrbf.AddContent(bookItem.Content);

                            btnResultDownload.NavigateUrl = lrbf.HttpPath;
                            btnResultDownload.Enabled = true;
                        }
                        catch (Exception ex)
                        {
                            Response.Write(ex.Message);
                        }
                    }
                }
            }

            btnResultDownload.Visible = Label3.Visible = true;

        }

        protected void btnSaveDirect_Click(object sender, EventArgs e)
        {
            PageContent pc = new PageContent(txtUrl.Text, _proxyAddress);

            try
            {
                string origfilename=Path.GetFileName(new Uri(txtUrl.Text).LocalPath);
                string filename = txtTargetFileName.Text.Equals(string.Empty) ? origfilename : txtTargetFileName.Text.Replace("%origfilename%", origfilename);

                LibRuBookFile lrbf = new LibRuBookFile(Server.MapPath(Path.Combine(LibRuBookFile.FILEFOLDER, filename)));
                lrbf.AddContent(pc.Content);

                btnResultDownload.NavigateUrl = lrbf.HttpPath;
                btnResultDownload.Enabled = true;
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

        }
    }
}